# coding: utf-8

import json

from flask import request, views, current_app
from flask_jwt_extended import create_access_token, set_access_cookies, unset_jwt_cookies, jwt_required, get_jwt

from exts import rdb, db
from server.utils.restful import rest_success, rest_error


class UserLoginView(views.MethodView):
    @staticmethod
    def post():
        data = request.get_data().decode()
        user_info = json.loads(data)
        user = user_info.get("user")
        password = user_info.get("password")
        sql = "select * from user where user = :user and password = :password"
        result = db.session.execute(sql, params={"user": user, "password": password}).fetchone()
        if result is not None:
            token = create_access_token(user)
            response = rest_success("获取token成功", result)
            set_access_cookies(response, token)
            return response
        else:
            return rest_error("用户或密码错误")

    @staticmethod
    @jwt_required()
    def delete():
        response = rest_success("已经退出登录")
        jti = get_jwt()["jti"]
        unset_jwt_cookies(response)
        rdb.set(jti, "", ex=current_app.config["JWT_ACCESS_TOKEN_EXPIRES"])  # 设置令牌在多久之类不能登录
        return response
